/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.OrderReceiveInfo;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;

public class PreferenceManager {
    /**
     * name of preference
     */
    private static final String PREFERENCE_NAME = "saveInfo";

    private static SharedPreferences mSharedPreferences;
    private static PreferenceManager mPreferencemManager;
    private static SharedPreferences.Editor editor;

    private String SHARED_KEY_SETTING_NOTIFICATION = "shared_key_setting_notification";
    private String SHARED_KEY_SETTING_DELETE_NOTIFY = "shared_key_setting_delete_notify";
    private String SHARED_KEY_SETTING_SOUND = "shared_key_setting_sound";
    private String SHARED_KEY_SETTING_VIBRATE = "shared_key_setting_vibrate";
    private String SHARED_KEY_SETTING_SPEAKER = "shared_key_setting_speaker";
    private String SHARED_KEY_SETTING_VOICE_AUTO_PLAY = "shared_key_setting_voice_auto_play"; //语音信息自动播放控制
    private String SHARED_KEY_CONTACT_GROUP_MODEL = "SHARED_KEY_CONTACT_GROUP_MODEL"; //联系人是否分组显示
    private String SHARED_KEY_IS_FIRST_OPEN_APP = "SHARED_KEY_IS_FIRST_OPEN_APP"; //联系人是否分组显示


    private static String SHARED_KEY_SETTING_DELETE_MESSAGES_WHEN_EXIT_GROUP = "shared_key_setting_delete_messages_when_exit_group";
    private static String SHARED_KEY_SETTING_AUTO_ACCEPT_GROUP_INVITATION = "shared_key_setting_auto_accept_group_invitation";


    private static String SHARED_KEY_CURRENTUSER_USERNAME = "SHARED_KEY_CURRENTUSER_USERNAME";
    private static String SHARED_KEY_CURRENTUSER_USERID = "SHARED_KEY_CURRENTUSER_USERID";
    private static String SHARED_KEY_CURRENTUSER_SEX = "SHARED_KEY_CURRENTUSER_SEX";
    private static String SHARED_KEY_CURRENTUSER_PHONE_NUMBER = "SHARED_KEY_CURRENTUSER_PHONE_NUMBER";
    private static String SHARED_KEY_CURRENTUSER_INSTALLATION_ID = "HARED_KEY_CURRENTUSER_INSTALLATION_ID";
    //是否验证
    private static String SHARED_KEY_CURRENTUSER_PHONE_NUMBER_VERIFIED = "SHARED_KEY_CURRENTUSER_PHONE_NUMBER_VERIFIED";
    private static String SHARED_KEY_CURRENTUSER_NICK = "SHARED_KEY_CURRENTUSER_NICK";
    private static String SHARED_KEY_CURRENTUSER_AREA = "SHARED_KEY_CURRENTUSER_AREA";
    private static String SHARED_KEY_CURRENTUSER_AVATAR = "SHARED_KEY_CURRENTUSER_AVATAR";


    private static String SHARED_KEY_CALL_MIN_VIDEO_KBPS = "SHARED_KEY_CALL_MIN_VIDEO_KBPS";
    private static String SHARED_KEY_CALL_MAX_VIDEO_KBPS = "SHARED_KEY_CALL_Max_VIDEO_KBPS";
    private static String SHARED_KEY_CALL_MAX_FRAME_RATE = "SHARED_KEY_CALL_MAX_FRAME_RATE";
    private static String SHARED_KEY_CALL_AUDIO_SAMPLE_RATE = "SHARED_KEY_CALL_AUDIO_SAMPLE_RATE";
    private static String SHARED_KEY_CALL_BACK_CAMERA_RESOLUTION = "SHARED_KEY_CALL_BACK_CAMERA_RESOLUTION";
    private static String SHARED_KEY_CALL_FRONT_CAMERA_RESOLUTION = "SHARED_KEY_FRONT_CAMERA_RESOLUTIOIN";
    private static String SHARED_KEY_CALL_FIX_SAMPLE_RATE = "SHARED_KEY_CALL_FIX_SAMPLE_RATE";

    private static String SHARED_KEY_SETTING_OFFLINE_PUSH_CALL = "shared_key_setting_offline_push_call";

    private static final String CURRENT_USER_TOKEN = "token";
    private static final String LOGIN_USER_TYPE = "type";
    private static final String LOGIN_USER_STATUS = "status";
    private static final String CURRENT_USER_WAN_TU_TOKEN = "wanTuToken";
    private static final String CURRENT_USER_BALANCE = "balance";
    private static final String CURRENT_USER_ALI_UID = "ali_uid";
    private static final String CURRENT_USER_ALI_ACCOUNT = "ali_account";
    private static final String CURRENT_USER_SEARCH_HISTORY_TOPIC = "search_history_topic";
    private static final String CURRENT_USER_SEARCH_HISTORY_LIVE_ROOM = "search_history_live_room";
    private static final String CURRENT_USER_ORDER_RECEIVE_INFO = "order_receive_info";
    private static final String CURRENT_USER_LIVE_ROOM_SUPPER_MANAGER = "live_room_supper_manager";
    private static final String CURRENT_USER_PAY_LIMIT = "pay_limit";//免密支付额度
    private static final String CURRENT_USER_DEPOSIT = "deposit";//免密支付额度

    private static final String TEMP_LOGIN_COUNT = "tempLoginCount";
    private static final String HIDE_PHONE = "hide_phone";


    private PreferenceManager(Context cxt) {
        mSharedPreferences = cxt.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        editor = mSharedPreferences.edit();
    }

    public static synchronized void init(Context cxt) {
        if (mPreferencemManager == null) {
            mPreferencemManager = new PreferenceManager(cxt);
        }
    }


    public synchronized static PreferenceManager getInstance() {
        if (mPreferencemManager == null) {
            throw new RuntimeException("please setupView first!");
        }
        return mPreferencemManager;
    }

    public void setSettingMsgNotification(boolean paramBoolean) {
        editor.putBoolean(SHARED_KEY_SETTING_NOTIFICATION, paramBoolean);
        editor.commit();
    }

    public boolean getSettingMsgNotification() {
        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_NOTIFICATION, true);
    }

    public void setSettingMsgDeleteNotify(Boolean paramBoolean) {
        editor.putBoolean(SHARED_KEY_SETTING_DELETE_NOTIFY, paramBoolean);
        editor.commit();
    }

    //默认好友关系解除不通知
    public boolean getSettingMsgDeleteNotify() {
        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_DELETE_NOTIFY, false);
    }


    public void setSettingMsgSound(boolean paramBoolean) {
        editor.putBoolean(SHARED_KEY_SETTING_SOUND, paramBoolean);
        editor.commit();
    }

    public boolean getSettingMsgSound() {

        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_SOUND, true);
    }

    public void setSettingMsgVibrate(boolean paramBoolean) {
        editor.putBoolean(SHARED_KEY_SETTING_VIBRATE, paramBoolean);
        editor.commit();
    }

    public boolean getSettingMsgVibrate() {
        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_VIBRATE, true);
    }

    public void setSettingMsgSpeaker(boolean paramBoolean) {
        editor.putBoolean(SHARED_KEY_SETTING_SPEAKER, paramBoolean);
        editor.commit();
    }

    public boolean getSettingMsgSpeaker() {
        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_SPEAKER, true);
    }

    public void setSettingVoiceAutoPlay(boolean paramBoolean) {
        editor.putBoolean(SHARED_KEY_SETTING_VOICE_AUTO_PLAY, paramBoolean);
        editor.commit();
    }

    public boolean getSettingVoiceAutoPlay() {
        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_VOICE_AUTO_PLAY, false);
    }

    public void setSettingContactGroup(boolean grouping) {
        editor.putBoolean(SHARED_KEY_CONTACT_GROUP_MODEL, grouping);
        editor.commit();
    }

    public boolean getSettingContactGroup() {
        return mSharedPreferences.getBoolean(SHARED_KEY_CONTACT_GROUP_MODEL, false);
    }

    public void setDeleteMessagesAsExitGroup(boolean value) {
        editor.putBoolean(SHARED_KEY_SETTING_DELETE_MESSAGES_WHEN_EXIT_GROUP, value);
        editor.commit();
    }

    public boolean isDeleteMessagesAsExitGroup() {
        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_DELETE_MESSAGES_WHEN_EXIT_GROUP, true);
    }

    public void setAutoAcceptGroupInvitation(boolean value) {
        editor.putBoolean(SHARED_KEY_SETTING_AUTO_ACCEPT_GROUP_INVITATION, value);
        editor.commit();
    }

    public boolean isAutoAcceptGroupInvitation() {
        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_AUTO_ACCEPT_GROUP_INVITATION, true);
    }


    public void setUserNick(String nick) {
        editor.putString(SHARED_KEY_CURRENTUSER_NICK, nick);
        editor.commit();
    }

    public void setUserAvatar(String avatar) {
        editor.putString(SHARED_KEY_CURRENTUSER_AVATAR, avatar);
        editor.commit();
    }

    public String getUserNick() {
        return mSharedPreferences.getString(SHARED_KEY_CURRENTUSER_NICK, null);
    }

    public String getUserArea() {
        return mSharedPreferences.getString(SHARED_KEY_CURRENTUSER_AREA, null);
    }

    public void setUserArea(String area) {
        editor.putString(SHARED_KEY_CURRENTUSER_AREA, area);
        editor.commit();
    }

    public String getUserAvatar() {
        return mSharedPreferences.getString(SHARED_KEY_CURRENTUSER_AVATAR, null);
    }

    public void setUserName(String username) {
        editor.putString(SHARED_KEY_CURRENTUSER_USERNAME, username);
        editor.commit();
    }


    public String getUsername() {
        return mSharedPreferences.getString(SHARED_KEY_CURRENTUSER_USERNAME, null);
    }

    public void setUserID(String currentUserID) {
        editor.putString(SHARED_KEY_CURRENTUSER_USERID, currentUserID);
        editor.commit();
    }

    public String getUserId() {
        return mSharedPreferences.getString(SHARED_KEY_CURRENTUSER_USERID, null);
    }

    public void setUserGender(Integer sex) {
        editor.putInt(SHARED_KEY_CURRENTUSER_SEX, sex);
        editor.commit();
    }

    public Integer getUserGender() {
        return mSharedPreferences.getInt(SHARED_KEY_CURRENTUSER_SEX, 0);
    }

    public void setCurrentuserPhoneNumber(String phoneNumber) {
        editor.putString(SHARED_KEY_CURRENTUSER_PHONE_NUMBER, phoneNumber);
        editor.commit();
    }

    public String getCurrentuserPhoneNumber() {
        return mSharedPreferences.getString(SHARED_KEY_CURRENTUSER_PHONE_NUMBER, null);
    }

    public void setCurrentuserInstallationId(String installationId) {
        editor.putString(SHARED_KEY_CURRENTUSER_INSTALLATION_ID, installationId);
        editor.commit();
    }

    public String getCurrentuserInstallationId() {
        return mSharedPreferences.getString(SHARED_KEY_CURRENTUSER_INSTALLATION_ID, null);
    }

    public void setCurrentUserPhoneNumberVerified(boolean verified) {
        editor.putBoolean(SHARED_KEY_CURRENTUSER_PHONE_NUMBER_VERIFIED, verified);
        editor.commit();
    }

    public boolean getCurrentUserPhoneNumberVerified() {
        return mSharedPreferences.getBoolean(SHARED_KEY_CURRENTUSER_PHONE_NUMBER_VERIFIED, false);
    }

    public void removeCurrentUserInfo() {
        editor.remove(CURRENT_USER_TOKEN);
        editor.remove(CURRENT_USER_SEARCH_HISTORY_TOPIC);
        editor.remove(CURRENT_USER_SEARCH_HISTORY_LIVE_ROOM);
        editor.remove(CURRENT_USER_ALI_UID);
        editor.remove(CURRENT_USER_BALANCE);
        editor.remove(CURRENT_USER_WAN_TU_TOKEN);
        editor.remove(SHARED_KEY_CURRENTUSER_NICK);
        editor.remove(SHARED_KEY_CURRENTUSER_AVATAR);
        // editor.remove(SHARED_KEY_CURRENTUSER_PHONE_NUMBER);//电话号码不清空，是为了让用户下次登录的时候，能显示上一次的登录用户名
        editor.remove(SHARED_KEY_CURRENTUSER_USERID);
        editor.remove(SHARED_KEY_CURRENTUSER_SEX);
        editor.remove(CURRENT_USER_PAY_LIMIT);
        //editor.remove(LOGIN_USER_TYPE);不清除，用于自动登录判断用户类型
        editor.remove(SHARED_KEY_CONTACT_GROUP_MODEL);
        editor.remove(CURRENT_USER_LIVE_ROOM_SUPPER_MANAGER);
        editor.commit();
    }


    public void setPushCall(boolean value) {
        editor.putBoolean(SHARED_KEY_SETTING_OFFLINE_PUSH_CALL, value);
        editor.apply();
    }

    public boolean isPushCall() {
        return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_OFFLINE_PUSH_CALL, false);
    }


    /**
     * ----------------------------------------- Call Option -----------------------------------------
     */

    /**
     * Min Video kbps
     * if no value was set, return -1
     *
     * @return
     */
    public int getCallMinVideoKbps() {
        return mSharedPreferences.getInt(SHARED_KEY_CALL_MIN_VIDEO_KBPS, -1);
    }

    public void setCallMinVideoKbps(int minBitRate) {
        editor.putInt(SHARED_KEY_CALL_MIN_VIDEO_KBPS, minBitRate);
        editor.apply();
    }

    /**
     * Max Video kbps
     * if no value was set, return -1
     *
     * @return
     */
    public int getCallMaxVideoKbps() {
        return mSharedPreferences.getInt(SHARED_KEY_CALL_MAX_VIDEO_KBPS, -1);
    }

    public void setCallMaxVideoKbps(int maxBitRate) {
        editor.putInt(SHARED_KEY_CALL_MAX_VIDEO_KBPS, maxBitRate);
        editor.apply();
    }

    /**
     * Max frame rate
     * if no value was set, return -1
     *
     * @return
     */
    public int getCallMaxFrameRate() {
        return mSharedPreferences.getInt(SHARED_KEY_CALL_MAX_FRAME_RATE, -1);
    }

    public void setCallMaxFrameRate(int maxFrameRate) {
        editor.putInt(SHARED_KEY_CALL_MAX_FRAME_RATE, maxFrameRate);
        editor.apply();
    }

    /**
     * audio sample rate
     * if no value was set, return -1
     *
     * @return
     */
    public int getCallAudioSampleRate() {
        return mSharedPreferences.getInt(SHARED_KEY_CALL_AUDIO_SAMPLE_RATE, -1);
    }

    public void setCallAudioSampleRate(int audioSampleRate) {
        editor.putInt(SHARED_KEY_CALL_AUDIO_SAMPLE_RATE, audioSampleRate);
        editor.apply();
    }

    /**
     * back camera resolution
     * format: 320x240
     * if no value was set, return ""
     */
    public String getCallBackCameraResolution() {
        return mSharedPreferences.getString(SHARED_KEY_CALL_BACK_CAMERA_RESOLUTION, "");
    }

    public void setCallBackCameraResolution(String resolution) {
        editor.putString(SHARED_KEY_CALL_BACK_CAMERA_RESOLUTION, resolution);
        editor.apply();
    }

    /**
     * front camera resolution
     * format: 320x240
     * if no value was set, return ""
     */
    public String getCallFrontCameraResolution() {
        return mSharedPreferences.getString(SHARED_KEY_CALL_FRONT_CAMERA_RESOLUTION, "");
    }

    public void setCallFrontCameraResolution(String resolution) {
        editor.putString(SHARED_KEY_CALL_FRONT_CAMERA_RESOLUTION, resolution);
        editor.apply();
    }

    /**
     * fixed video sample rate
     * if no value was set, return false
     *
     * @return
     */
    public boolean isCallFixedVideoResolution() {
        return mSharedPreferences.getBoolean(SHARED_KEY_CALL_FIX_SAMPLE_RATE, false);
    }

    public void setCallFixedVideoResolution(boolean enable) {
        editor.putBoolean(SHARED_KEY_CALL_FIX_SAMPLE_RATE, enable);
        editor.apply();
    }

    public void setCurrentUserToken(String token) {
        editor.putString(CURRENT_USER_TOKEN, token);
        editor.commit();
    }

    public String getCurrentUserToken() {
        return mSharedPreferences.getString(CURRENT_USER_TOKEN, null);
    }

    public void setWanTuToken(String wanTuToken) {
        editor.putString(CURRENT_USER_WAN_TU_TOKEN, wanTuToken);
        editor.commit();
    }

    public String getWanTuToken() {
        return mSharedPreferences.getString(CURRENT_USER_WAN_TU_TOKEN, "");
    }

    public void setUserBalance(double balance) {
        editor.putFloat(CURRENT_USER_BALANCE, (float) balance);
        editor.commit();
    }

    public double getUserBalance() {
        float aFloat = mSharedPreferences.getFloat(CURRENT_USER_BALANCE, 0F);

        return new BigDecimal(aFloat).setScale(2, RoundingMode.HALF_DOWN).doubleValue();
    }

    public void setCurrentUserAliUid(String aliUid) {
        editor.putString(CURRENT_USER_ALI_UID, aliUid);
        editor.commit();
    }

    public void setCurrentUserAliAccount(String aliAccount) {
        editor.putString(CURRENT_USER_ALI_ACCOUNT, aliAccount);
        editor.commit();
    }

    public String getCurrentUserAliAccount() {
        return mSharedPreferences.getString(CURRENT_USER_ALI_ACCOUNT, "");
    }

    public String getCurrentUserAliUid() {
        return mSharedPreferences.getString(CURRENT_USER_ALI_UID, "");
    }

    public List<String> getCurrentUserSearchHistoryTopic() {

        String string = mSharedPreferences.getString(CURRENT_USER_SEARCH_HISTORY_TOPIC, null);
        return JSONObject.parseArray(string, String.class);
    }

    public void setCurrentUserSearchHistoryTopic(List<String> searchHistoryList) {
        String jsonString = JSONObject.toJSONString(searchHistoryList);
        editor.putString(CURRENT_USER_SEARCH_HISTORY_TOPIC, jsonString);
        editor.commit();
    }

    public List<String> getCurrentUserSearchHistoryLiveRoom() {
        String string = mSharedPreferences.getString(CURRENT_USER_SEARCH_HISTORY_LIVE_ROOM, null);
        return JSONArray.parseArray(string, String.class);
    }

    public void setCurrentUserSearchHistoryLiveRoom(List<String> searchHistoryList) {
        String string = JSONObject.toJSONString(searchHistoryList);
        editor.putString(CURRENT_USER_SEARCH_HISTORY_LIVE_ROOM, string);
        editor.commit();
    }

    public void setCurrentUserPayLimit(int payLimit) {
        editor.putInt(CURRENT_USER_PAY_LIMIT, payLimit);
        editor.commit();
    }

    public int getCurrentUserPayLimit() {
        return mSharedPreferences.getInt(CURRENT_USER_PAY_LIMIT, Constant.ORIGINAL_PAY_PASSWORD_);//返回-1，表示没有设置过 支付密码
    }


    public int getTempLoginCount() {
        return mSharedPreferences.getInt(TEMP_LOGIN_COUNT, 1);
    }

    public void setTempLoginCount(int count) {
        editor.putInt(TEMP_LOGIN_COUNT, count);
        editor.commit();
    }


    public void setSearchUserInfo(boolean isChecked) {
        editor.putBoolean(HIDE_PHONE, isChecked);
        editor.commit();
    }

    public boolean isSearchUserInfo() {
        return mSharedPreferences.getBoolean(HIDE_PHONE, false);//默认false,关闭隐身模式，可以被搜索
    }

    public void setUserDeposit(double deposit) {
        editor.putFloat(CURRENT_USER_DEPOSIT, (float) deposit);
        editor.commit();
    }

    public double getUserDeposit() {
        return mSharedPreferences.getFloat(CURRENT_USER_DEPOSIT, 0);

    }

    public List<OrderReceiveInfo> getOrderReceiveInfoList() {
        String string = mSharedPreferences.getString(CURRENT_USER_ORDER_RECEIVE_INFO, null);
        if (string != null) {
            return JSONObject.parseArray(string, OrderReceiveInfo.class);
        } else {
            return Collections.emptyList();
        }

    }

    public void setOrderReceiveInfoList(List<OrderReceiveInfo> orderReceiveInfoList) {
        String jsonString = JSONObject.toJSONString(orderReceiveInfoList);
        editor.putString(CURRENT_USER_ORDER_RECEIVE_INFO, jsonString);
        editor.commit();
    }

    public void setLiveRoomSupperManager(boolean liveRoomSupperManager) {
        editor.putBoolean(CURRENT_USER_LIVE_ROOM_SUPPER_MANAGER, liveRoomSupperManager);
        editor.commit();
    }

    public boolean getLiveRoomSupperManager() {
        return mSharedPreferences.getBoolean(CURRENT_USER_LIVE_ROOM_SUPPER_MANAGER, false);
    }

    public void setType(Integer type) {
        editor.putInt(LOGIN_USER_TYPE, type);
        editor.commit();
    }

    public int getType() {
        return mSharedPreferences.getInt(LOGIN_USER_TYPE, Constant.USER_TYPE_TEMP);//默认返回 临时用户的类型，因为第一次安装app 后，是按临时用户处理自动登录的逻辑，
    }


    public void setStatus(int status) {
        editor.putInt(LOGIN_USER_STATUS, status);
        editor.commit();
    }

    public int getStatus() {
        return mSharedPreferences.getInt(LOGIN_USER_STATUS, Constant.USER_STATUS_NORMAL);
    }

    public boolean isFirstOpenApp() {
        return mSharedPreferences.getBoolean(SHARED_KEY_IS_FIRST_OPEN_APP, true);
    }

    public void setIsFirstOpenApp(boolean b) {
        editor.putBoolean(SHARED_KEY_IS_FIRST_OPEN_APP, b);
        editor.apply();
    }
}
